/**
 * AI角色管理服务
 * 负责角色的存储、管理和System Prompt生成
 */

import { GenericStorageAdapter } from '../storage/genericStorageAdapter'
import { StorageResult } from '../storage/types'
import { 
  AIRole, 
  CreateRoleRequest, 
  UpdateRoleRequest, 
  ROLE_STORAGE_KEYS,
  RoleCategory,
  AIRoleResult,
  AIRoleError
} from './types'
import { getBuiltInRoles, getBuiltInRoleById } from './builtInRoles'
import { promptTemplateEngine } from './promptTemplate'

export class AIRoleService {
  private storageAdapter: GenericStorageAdapter

  constructor(storageAdapter: GenericStorageAdapter) {
    this.storageAdapter = storageAdapter
  }

  /**
   * 创建错误对象的辅助方法
   */
  private createError(code: string, message: string, details?: any) {
    return {
      code,
      message,
      details
    }
  }

  /**
   * 获取所有角色（预设+自定义）
   */
  async getAllRoles(): Promise<StorageResult<AIRole[]>> {
    console.log('[角色服务] 获取所有角色')
    
    try {
      const builtInRoles = getBuiltInRoles()
      const customRolesResult = await this.getCustomRoles()
      
      if (!customRolesResult.ok) {
        // 如果获取自定义角色失败，仍然返回预设角色
        console.warn('[角色服务] 获取自定义角色失败，仅返回预设角色')
        return {
          ok: true,
          data: builtInRoles
        }
      }

      const allRoles = [...builtInRoles, ...customRolesResult.data]
      
      console.log('[角色服务] 成功获取角色', {
        builtInCount: builtInRoles.length,
        customCount: customRolesResult.data.length,
        totalCount: allRoles.length
      })

      return {
        ok: true,
        data: allRoles
      }
    } catch (error) {
      console.error('[角色服务] 获取角色失败', error)
      return {
        ok: false,
        error: {
          code: 'get_roles_failed',
          message: '获取角色列表失败',
          details: error
        }
      }
    }
  }

  /**
   * 获取预设角色
   */
  getBuiltInRoles(): AIRole[] {
    return getBuiltInRoles()
  }

  /**
   * 获取自定义角色
   */
  async getCustomRoles(): Promise<StorageResult<AIRole[]>> {
    const result = await this.storageAdapter.getItem<AIRole[]>(ROLE_STORAGE_KEYS.ROLES)
    
    if (!result.ok) {
      return result
    }

    if (result.data === null) {
      // 首次使用，返回空数组
      return {
        ok: true,
        data: []
      }
    }

    return result
  }

  /**
   * 根据ID获取角色
   */
  async getRoleById(roleId: string): Promise<StorageResult<AIRole | null>> {
    console.log('[角色服务] 获取角色', { roleId })

    // 先检查预设角色
    const builtInRole = getBuiltInRoleById(roleId)
    if (builtInRole) {
      return {
        ok: true,
        data: builtInRole
      }
    }

    // 检查自定义角色
    const customRolesResult = await this.getCustomRoles()
    if (!customRolesResult.ok) {
      return {
        ok: false,
        error: customRolesResult.error
      }
    }

    const customRole = customRolesResult.data.find(role => role.id === roleId)
    return {
      ok: true,
      data: customRole || null
    }
  }

  /**
   * 创建自定义角色
   */
  async createCustomRole(request: CreateRoleRequest): Promise<StorageResult<AIRole>> {
    console.log('[角色服务] 创建自定义角色', { name: request.name })

    try {
      const now = new Date()
      const role: AIRole = {
        id: this.generateRoleId(),
        ...request,
        isBuiltIn: false,
        createdAt: now,
        updatedAt: now
      }

      // 验证角色数据
      const validationResult = this.validateRole(role)
      if (!validationResult.isValid) {
        return {
          ok: false,
          error: {
            code: 'validation_failed',
            message: '角色数据验证失败',
            details: validationResult.errors
          }
        }
      }

      // 获取现有自定义角色
      const customRolesResult = await this.getCustomRoles()
      if (!customRolesResult.ok) {
        return {
          ok: false,
          error: customRolesResult.error
        }
      }

      // 检查名称是否重复
      const existingRole = customRolesResult.data.find(r => r.name === role.name)
      if (existingRole) {
        return {
          ok: false,
          error: {
            code: 'role_name_exists',
            message: '角色名称已存在',
            details: { name: role.name }
          }
        }
      }

      // 保存角色
      const updatedRoles = [...customRolesResult.data, role]
      const saveResult = await this.storageAdapter.setItem(ROLE_STORAGE_KEYS.ROLES, updatedRoles)
      
      if (!saveResult.ok) {
        return {
          ok: false,
          error: saveResult.error
        }
      }

      console.log('[角色服务] 成功创建角色', { roleId: role.id, name: role.name })
      return {
        ok: true,
        data: role
      }
    } catch (error) {
      console.error('[角色服务] 创建角色失败', error)
      return {
        ok: false,
        error: {
          code: 'create_role_failed',
          message: '创建角色失败',
          details: error
        }
      }
    }
  }

  /**
   * 更新角色
   */
  async updateRole(roleId: string, updates: UpdateRoleRequest): Promise<StorageResult<AIRole>> {
    console.log('[角色服务] 更新角色', { roleId, updates })

    try {
      // 检查是否为预设角色
      const builtInRole = getBuiltInRoleById(roleId)
      if (builtInRole) {
        return {
          ok: false,
          error: {
            code: 'builtin_role_readonly',
            message: '预设角色不可修改',
            details: { roleId }
          }
        }
      }

      // 获取自定义角色
      const customRolesResult = await this.getCustomRoles()
      if (!customRolesResult.ok) {
        return {
          ok: false,
          error: customRolesResult.error
        }
      }

      const roleIndex = customRolesResult.data.findIndex(r => r.id === roleId)
      if (roleIndex === -1) {
        return {
          ok: false,
          error: {
            code: 'role_not_found',
            message: '角色不存在',
            details: { roleId }
          }
        }
      }

      // 更新角色
      const existingRole = customRolesResult.data[roleIndex]
      const updatedRole: AIRole = {
        ...existingRole,
        ...updates,
        id: roleId,  // 确保ID不被更改
        isBuiltIn: false,  // 确保不是预设角色
        updatedAt: new Date()
      }

      // 验证更新后的角色
      const validationResult = this.validateRole(updatedRole)
      if (!validationResult.isValid) {
        return {
          ok: false,
          error: {
            code: 'validation_failed',
            message: '角色数据验证失败',
            details: validationResult.errors
          }
        }
      }

      // 保存更新
      const updatedRoles = [...customRolesResult.data]
      updatedRoles[roleIndex] = updatedRole

      const saveResult = await this.storageAdapter.setItem(ROLE_STORAGE_KEYS.ROLES, updatedRoles)
      if (!saveResult.ok) {
        return {
          ok: false,
          error: saveResult.error
        }
      }

      console.log('[角色服务] 成功更新角色', { roleId })
      return {
        ok: true,
        data: updatedRole
      }
    } catch (error) {
      console.error('[角色服务] 更新角色失败', error)
      return {
        ok: false,
        error: {
          code: 'update_role_failed',
          message: '更新角色失败',
          details: error
        }
      }
    }
  }

  /**
   * 删除自定义角色
   */
  async deleteRole(roleId: string): Promise<StorageResult<void>> {
    console.log('[角色服务] 删除角色', { roleId })

    try {
      // 检查是否为预设角色
      const builtInRole = getBuiltInRoleById(roleId)
      if (builtInRole) {
        return {
          ok: false,
          error: {
            code: 'builtin_role_readonly',
            message: '预设角色不可删除',
            details: { roleId }
          }
        }
      }

      // 获取自定义角色
      const customRolesResult = await this.getCustomRoles()
      if (!customRolesResult.ok) {
        return {
          ok: false,
          error: customRolesResult.error
        }
      }

      const roleIndex = customRolesResult.data.findIndex(r => r.id === roleId)
      if (roleIndex === -1) {
        return {
          ok: false,
          error: {
            code: 'role_not_found',
            message: '角色不存在',
            details: { roleId }
          }
        }
      }

      // 删除角色
      const updatedRoles = customRolesResult.data.filter(r => r.id !== roleId)
      const saveResult = await this.storageAdapter.setItem(ROLE_STORAGE_KEYS.ROLES, updatedRoles)
      
      if (!saveResult.ok) {
        return {
          ok: false,
          error: saveResult.error
        }
      }

      // 如果删除的是当前角色，清除当前角色设置
      const currentRoleResult = await this.getCurrentRole()
      if (currentRoleResult.ok && currentRoleResult.data?.id === roleId) {
        await this.setCurrentRole(null)
      }

      console.log('[角色服务] 成功删除角色', { roleId })
      return {
        ok: true,
        data: undefined
      }
    } catch (error) {
      console.error('[角色服务] 删除角色失败', error)
      return {
        ok: false,
        error: {
          code: 'delete_role_failed',
          message: '删除角色失败',
          details: error
        }
      }
    }
  }

  /**
   * 设置当前角色
   */
  async setCurrentRole(roleId: string | null): Promise<StorageResult<void>> {
    console.log('[角色服务] 设置当前角色', { roleId })

    if (roleId) {
      // 验证角色是否存在
      const roleResult = await this.getRoleById(roleId)
      if (!roleResult.ok) {
        return {
          ok: false,
          error: roleResult.error
        }
      }
      if (!roleResult.data) {
        return {
          ok: false,
          error: {
            code: 'role_not_found',
            message: '角色不存在',
            details: { roleId }
          }
        }
      }
    }

    const result = await this.storageAdapter.setItem(ROLE_STORAGE_KEYS.CURRENT_ROLE, roleId)
    if (result.ok) {
      console.log('[角色服务] 成功设置当前角色', { roleId })
    }
    return result
  }

  /**
   * 获取当前角色
   */
  async getCurrentRole(): Promise<StorageResult<AIRole | null>> {
    const currentRoleIdResult = await this.storageAdapter.getItem<string>(ROLE_STORAGE_KEYS.CURRENT_ROLE)
    
    if (!currentRoleIdResult.ok) {
      return {
        ok: false,
        error: currentRoleIdResult.error
      }
    }

    if (currentRoleIdResult.data === null) {
      return {
        ok: true,
        data: null
      }
    }

    const roleId = currentRoleIdResult.data
    if (!roleId) {
      return {
        ok: true,
        data: null
      }
    }

    return await this.getRoleById(roleId)
  }

  /**
   * 根据角色生成System Prompt
   */
  generateSystemPrompt(role: AIRole, context?: Record<string, any>): string {
    console.log('[角色服务] 生成System Prompt', { roleId: role.id, roleName: role.name })

    const variables = {
      ...role.settings,
      ...context
    }

    try {
      const prompt = promptTemplateEngine.render(role.systemPrompt, variables)
      console.log('[角色服务] System Prompt生成成功', {
        promptLength: prompt.length,
        variables: Object.keys(variables)
      })
      return prompt
    } catch (error) {
      console.error('[角色服务] System Prompt生成失败', error)
      // 返回原始模板作为降级方案
      return role.systemPrompt
    }
  }

  /**
   * 生成角色ID
   */
  private generateRoleId(): string {
    return `custom_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 验证角色数据
   */
  private validateRole(role: AIRole): { isValid: boolean; errors: string[] } {
    const errors: string[] = []

    if (!role.name || role.name.trim().length === 0) {
      errors.push('角色名称不能为空')
    }

    if (!role.description || role.description.trim().length === 0) {
      errors.push('角色描述不能为空')
    }

    if (!role.systemPrompt || role.systemPrompt.trim().length === 0) {
      errors.push('System Prompt不能为空')
    }

    if (!Object.values(RoleCategory).includes(role.category)) {
      errors.push('角色分类无效')
    }

    if (!Array.isArray(role.tags)) {
      errors.push('角色标签必须是数组')
    }

    if (!role.settings) {
      errors.push('角色设置不能为空')
    } else {
      if (typeof role.settings.temperature !== 'number' || 
          role.settings.temperature < 0 || 
          role.settings.temperature > 2) {
        errors.push('temperature参数必须在0-2之间')
      }
    }

    // 验证System Prompt模板
    const templateValidation = promptTemplateEngine.validateTemplate(role.systemPrompt)
    if (!templateValidation.isValid) {
      errors.push(...templateValidation.errors.map(e => `System Prompt模板错误: ${e}`))
    }

    return {
      isValid: errors.length === 0,
      errors
    }
  }

  /**
   * 根据分类获取角色
   */
  async getRolesByCategory(category: RoleCategory): Promise<StorageResult<AIRole[]>> {
    const allRolesResult = await this.getAllRoles()
    if (!allRolesResult.ok) {
      return allRolesResult
    }

    const rolesInCategory = allRolesResult.data.filter(role => role.category === category)
    return {
      ok: true,
      data: rolesInCategory
    }
  }

  /**
   * 搜索角色
   */
  async searchRoles(query: string): Promise<StorageResult<AIRole[]>> {
    const allRolesResult = await this.getAllRoles()
    if (!allRolesResult.ok) {
      return allRolesResult
    }

    const normalizedQuery = query.toLowerCase()
    const matchedRoles = allRolesResult.data.filter(role => 
      role.name.toLowerCase().includes(normalizedQuery) ||
      role.description.toLowerCase().includes(normalizedQuery) ||
      role.tags.some(tag => tag.toLowerCase().includes(normalizedQuery))
    )

    return {
      ok: true,
      data: matchedRoles
    }
  }

  /**
   * 导出自定义角色
   */
  async exportCustomRoles(): Promise<StorageResult<string>> {
    const customRolesResult = await this.getCustomRoles()
    if (!customRolesResult.ok) {
      return {
        ok: false,
        error: customRolesResult.error
      }
    }

    try {
      const exportData = {
        version: '1.0',
        exportTime: new Date().toISOString(),
        roles: customRolesResult.data
      }

      const jsonString = JSON.stringify(exportData, null, 2)
      return {
        ok: true,
        data: jsonString
      }
    } catch (error) {
      return {
        ok: false,
        error: {
          code: 'export_failed',
          message: '导出角色失败',
          details: error
        }
      }
    }
  }

  /**
   * 导入自定义角色
   */
  async importCustomRoles(jsonString: string, overwrite: boolean = false): Promise<StorageResult<number>> {
    try {
      const importData = JSON.parse(jsonString)
      
      if (!importData.roles || !Array.isArray(importData.roles)) {
        return {
          ok: false,
          error: {
            code: 'invalid_import_data',
            message: '导入数据格式错误',
            details: '缺少有效的角色数组'
          }
        }
      }

      const importRoles: AIRole[] = importData.roles
      let importedCount = 0

      const currentRolesResult = await this.getCustomRoles()
      if (!currentRolesResult.ok) {
        return {
          ok: false,
          error: currentRolesResult.error
        }
      }

      let existingRoles = currentRolesResult.data

      for (const role of importRoles) {
        // 验证角色数据
        const validationResult = this.validateRole(role)
        if (!validationResult.isValid) {
          console.warn('[角色服务] 跳过无效角色', { roleName: role.name, errors: validationResult.errors })
          continue
        }

        // 检查是否已存在
        const existingIndex = existingRoles.findIndex(r => r.name === role.name)
        
        if (existingIndex >= 0) {
          if (overwrite) {
            // 覆盖现有角色
            existingRoles[existingIndex] = {
              ...role,
              id: existingRoles[existingIndex].id,  // 保持原ID
              updatedAt: new Date()
            }
            importedCount++
          }
          // 否则跳过
        } else {
          // 添加新角色
          const newRole: AIRole = {
            ...role,
            id: this.generateRoleId(),
            isBuiltIn: false,
            createdAt: new Date(),
            updatedAt: new Date()
          }
          existingRoles.push(newRole)
          importedCount++
        }
      }

      // 保存更新的角色列表
      const saveResult = await this.storageAdapter.setItem(ROLE_STORAGE_KEYS.ROLES, existingRoles)
      if (!saveResult.ok) {
        return {
          ok: false,
          error: saveResult.error
        }
      }

      console.log('[角色服务] 成功导入角色', { importedCount })
      return {
        ok: true,
        data: importedCount
      }
    } catch (error) {
      return {
        ok: false,
        error: {
          code: 'import_failed',
          message: '导入角色失败',
          details: error
        }
      }
    }
  }
}